package com.knife.blog.mail;


import java.util.* ;   
import java.io.* ;   
import javax.mail.* ;   
import javax.mail.internet.* ;   
import javax.activation.* ;  
import com.knife.util.MD5;
import com.knife.blog.service.Config;


public class SendMail {   
    //定义发件人、收件人、SMTP服务器、用户名、密码、主题、内容等   
    private String displayName;  
    private String from;
    private String to;    
    private String cc;		//抄送
    private String bcc;	//暗送
    private String Priority; 	//优先级  1 最高 3 普通 5 缓慢  
    private String smtpServer;   
    private String username;   
    private String password;   
    private String subject;   
    private String content;   
    private boolean ifAuth; //服务器是否要身份认证     
    private Vector file = new Vector(); //用于保存发送附件的文件名的集合   
     
    private Session session;
      
    /**  
     * 设置SMTP服务器地址  
     */   
    public void setSmtpServer(String smtpServer){   
        this.smtpServer=smtpServer;   
    }   
        
    /**  
     * 设置显示的名称  
     */   
    public void setDisplayName(String displayName){   
        this.displayName=displayName;   
    }   
      
    /**  
     * 设置服务器是否需要身份认证  
     */   
    public void setIfAuth(boolean ifAuth){   
        this.ifAuth=ifAuth;   
    }   
      
    /**  
     * 设置E-mail用户名  
     */   
    public void setUserName(String username){   
        this.username=username;   
    }   
      
    /**  
     * 设置E-mail密码  
     */   
    public void setPassword(String password){   
        this.password=password;   
    }   
      
    /**  
     * 设置接收者  
     */   
    public void setTo(String to){   
        this.to=to;   
    }   
      
    /**
     * 设置抄送
     */
    public void setCC(String cc){
    	this.cc = cc;
    }
    
    /**
     * 设置暗送
     */
    public void setBCC(String bcc){
    	this.bcc = bcc;
    }
    /**  
     * 设置主题  
     */   
    public void setSubject(String subject){   
        this.subject=subject;   
    }   
      
    /**  
     * 设置主体内容  
     */   
    public void setContent(String content){   
        this.content=content;   
    }   
      
    /**
     * 设置邮件优先级
     */
    public void setPriority(String p){
    	
    	this.Priority = p;
    	
    }
    
    /**  
     * 该方法用于收集附件名  
     */   
    public void addAttachfile(String fname){   
        file.addElement(fname);   
    }   
      
    public void initAttach(){
    	file.clear();
    }
    /**
     * 
     *
     */
    public void addAttachfile(String realfname,String fname){
    	if(fname.equals("")){
    		String tmp = realfname.replaceAll("\\\\","/");
    		int pos = tmp.lastIndexOf("/");
    		fname=tmp.substring(pos+1);
    	}
    	HashMap<String,String> map=new HashMap<String,String>();
    	map.put("realfilename",realfname);
    	map.put("filename",fname);
    	file.addElement(map);
    }
    
    public SendMail(){   
    	this.bcc = "";
    	this.cc = "";
    	this.Priority = "3";
    	this.displayName = "";
    }   
      
    /**  
     * 初始化SMTP服务器地址、发送者E-mail地址、用户名、密码、接收者、主题、内容  
     */   
    public SendMail(String smtpServer,String from,String displayName,String username,String password,String to,String subject,String content){   
        this.smtpServer=smtpServer;   
        this.from=from;   
        this.displayName=displayName;   
        this.ifAuth=true;   
        this.username=username;   
        this.password=password;   
        this.to=to;   
        this.subject=subject;   
        this.content=content;   
        this.cc="";
        this.bcc="";
        this.Priority = "3";
        this.file=null;
    }   
      
    /**  
     * 初始化SMTP服务器地址、发送者E-mail地址、接收者、主题、内容  
     */   
    public SendMail(String smtpServer,String from,String displayName,String to,String subject,String content){   
        this.smtpServer=smtpServer;   
        this.from=from;   
        this.displayName=displayName;   
        this.ifAuth=false;   
        this.to=to;   
        this.subject=subject;   
        this.content=content;   
    }  
    
    public Transport initSend(String smtpServer,boolean ifAuth,String username,String password) throws Exception{    	
        //Properties props = System.getProperties();
        Properties props = new Properties();
        props.put("mail.smtp.host", smtpServer);           
        if(ifAuth){ //服务器需要身份认证   
            props.put("mail.smtp.auth","true");      
            MyAuthenticator smtpAuth=new MyAuthenticator(username,password);   
            //session=Session.getDefaultInstance(props, smtpAuth);
            session = Session.getInstance(props,smtpAuth);            
        }else{   
            props.put("mail.smtp.auth","false");   
            session=Session.getDefaultInstance(props, null);   
        }          
        session.setDebug(true);   
        Transport trans = null; 
        trans = session.getTransport("smtp");   
        trans.connect(smtpServer, username, password); 
        return(trans);
    }
    
    public void close(){
    	session = null;
    }
    public HashMap send(Transport trans){
    	HashMap map=new HashMap();   
        map.put("state", "success");   
        String message="邮件发送成功！";   
    
        try {   
            Message msg = new MimeMessage(session);    
            try{   
                Address from_address = new InternetAddress(from, displayName);   
                msg.setFrom(from_address);   
            }catch(java.io.UnsupportedEncodingException e){   
                e.printStackTrace();   
            }
            Address[] addrs=InternetAddress.parse(to);
            msg.setRecipients(Message.RecipientType.TO,addrs);   
            if(!cc.equals(""))
            	msg.setRecipient(Message.RecipientType.CC,new InternetAddress(cc));
            if(!bcc.equals(""))
            	msg.setRecipient(Message.RecipientType.BCC,new InternetAddress(bcc));
            msg.setSubject(subject);   
            Multipart mp = new MimeMultipart();   
            MimeBodyPart mbp = new MimeBodyPart();   
            mbp.setContent(content.toString(), "text/html;charset=gb2312");   
            mp.addBodyPart(mbp); 
            HashMap filemap = null;
            if(!file.isEmpty()){//有附件   
                Enumeration efile=file.elements();   
                while(efile.hasMoreElements()){    
                    mbp=new MimeBodyPart();   
                    filemap=(HashMap)efile.nextElement(); //选择出每一个附件map   
                    FileDataSource fds=new FileDataSource((String)filemap.get("realfilename")); //得到数据源   
                    mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart   
                    try{
                    	//System.out.println("要发送的附件名："+fds.getName());
                    	mbp.setFileName(MimeUtility.encodeText((String)filemap.get("filename")));  //得到文件名同样至入BodyPart   
                    }catch(UnsupportedEncodingException e){
                    	mbp.setFileName(fds.getName());
                    }
                    mp.addBodyPart(mbp);   
                }     
                file.removeAllElements();       
            }    
            msg.setContent(mp); //Multipart加入到信件   
            msg.setSentDate(new Date());     //设置信件头的发送日期   
            //msg.setHeader("Content-Transfer-Encoding","base64");
      	  	msg.setHeader("X-Mailer","TurboMail Sender");
      	  	msg.setHeader("X-Priority",Priority);
      	  //	msg.setHeader("Disposition-Notification-To",from);
            //发送信件   
            msg.saveChanges();                   
            trans.sendMessage(msg, msg.getAllRecipients());   
            trans.close();                
        }catch(AuthenticationFailedException e){      
             map.put("state", "failed");   
             message="邮件发送失败！错误原因：\n"+"身份验证错误!";   
             e.printStackTrace();    
        }catch (MessagingException e) {   
             message="邮件发送失败！错误原因：\n"+e.getMessage();   
             map.put("state", "failed");   
             e.printStackTrace();   
             Exception ex = null;   
             if ((ex = e.getNextException()) != null) {   
                 System.out.println(ex.toString());   
                 ex.printStackTrace();   
             }    
        }   
        //session = null;
        //System.out.println("\n提示信息:"+message);   
        map.put("message", message);         
        return map;  
    }
    /**  
     * 发送邮件  
     */   
    @SuppressWarnings("unchecked")
	public HashMap send(){   
        HashMap map=new HashMap();   
        map.put("state", "success");   
        String message="邮件发送成功！";   
        Session session=null;   
        //Properties props = System.getProperties();
        Properties props = new Properties();
        props.put("mail.smtp.host", smtpServer);           
        if(ifAuth){ //服务器需要身份认证   
            props.put("mail.smtp.auth","true");      
            MyAuthenticator smtpAuth=new MyAuthenticator(username,password);   
            //session=Session.getDefaultInstance(props, smtpAuth);
            session = Session.getInstance(props,smtpAuth);            
        }else{   
            props.put("mail.smtp.auth","false");   
            session=Session.getDefaultInstance(props, null);   
        }          
        session.setDebug(true);   
        Transport trans = null;     
        try {   
            Message msg = new MimeMessage(session);    
            try{   
                Address from_address = new InternetAddress(from, displayName);   
                msg.setFrom(from_address);   
            }catch(java.io.UnsupportedEncodingException e){   
                e.printStackTrace();   
            }
            Address[] addrs=InternetAddress.parse(to);
            msg.setRecipients(Message.RecipientType.TO,addrs);   
            if(!cc.equals(""))
            	msg.setRecipient(Message.RecipientType.CC,new InternetAddress(cc));
            if(!bcc.equals(""))
            	msg.setRecipient(Message.RecipientType.BCC,new InternetAddress(bcc));
            msg.setSubject(subject);   
            Multipart mp = new MimeMultipart();   
            MimeBodyPart mbp = new MimeBodyPart();   
            mbp.setContent(content.toString(), "text/html;charset=gb2312");   
            mp.addBodyPart(mbp); 
            HashMap filemap = null;
            if(!file.isEmpty()){//有附件   
                Enumeration efile=file.elements();   
                while(efile.hasMoreElements()){    
                    mbp=new MimeBodyPart();   
                    filemap=(HashMap)efile.nextElement(); //选择出每一个附件map   
                    FileDataSource fds=new FileDataSource((String)filemap.get("realfilename")); //得到数据源   
                    mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart   
                    try{
                    	//System.out.println("要发送的附件名："+fds.getName());
                    	mbp.setFileName(MimeUtility.encodeText((String)filemap.get("filename")));  //得到文件名同样至入BodyPart   
                    }catch(UnsupportedEncodingException e){
                    	mbp.setFileName(fds.getName());
                    }
                    mp.addBodyPart(mbp);   
                }     
                file.removeAllElements();       
            }    
            msg.setContent(mp); //Multipart加入到信件   
            msg.setSentDate(new Date());     //设置信件头的发送日期   
            //msg.setHeader("Content-Transfer-Encoding","base64");
      	  	msg.setHeader("X-Mailer","TurboMail Sender");
      	  	msg.setHeader("X-Priority",Priority);
      	  	//msg.setHeader("Disposition-Notification-To",from);
            //发送信件   
            msg.saveChanges();    
            trans = session.getTransport("smtp");   
            trans.connect(smtpServer, username, password);   
            trans.sendMessage(msg, msg.getAllRecipients());   
            trans.close();                
        }catch(AuthenticationFailedException e){      
             map.put("state", "failed");   
             message="邮件发送失败！错误原因：\n"+"身份验证错误!";   
             e.printStackTrace();    
        }catch (MessagingException e) {   
             message="邮件发送失败！错误原因：\n"+e.getMessage();   
             map.put("state", "failed");   
             e.printStackTrace();   
             Exception ex = null;   
             if ((ex = e.getNextException()) != null) {   
                 System.out.println(ex.toString());   
                 ex.printStackTrace();   
             }    
        }   
        session = null;
        //System.out.println("\n提示信息:"+message);   
        map.put("message", message);         
        return map;   
    } 
    
    /**  
     * 一个附件一封邮件发送邮件  
     */   
    @SuppressWarnings("unchecked")
	public HashMap msend(){   
        HashMap map=new HashMap();   
        map.put("state", "success");   
        String message="邮件发送成功！";   
        Session session=null;   
        //Properties props = System.getProperties();
        Properties props = new Properties();
        props.put("mail.smtp.host", smtpServer);           
        if(ifAuth){ //服务器需要身份认证   
            props.put("mail.smtp.auth","true");      
            MyAuthenticator smtpAuth=new MyAuthenticator(username,password);   
            //session=Session.getDefaultInstance(props, smtpAuth);
            session = Session.getInstance(props,smtpAuth);            
        }else{   
            props.put("mail.smtp.auth","false");   
            session=Session.getDefaultInstance(props, null);   
        }
        Transport trans = null;               
        session.setDebug(true);               
        try {   
        	trans = session.getTransport("smtp");                   
        	if(!trans.isConnected()) trans.connect(smtpServer, username, password);         	
            for(int i=0;i<file.size();i++){
            	if(!trans.isConnected()) trans.connect(smtpServer, username, password); 
            	System.out.println("发送开始时间："+new Date());
            	HashMap filemap = (HashMap) file.get(i);            
            	//每个文件一封邮件附件
            	Message msg = new MimeMessage(session);                    
                try{   
                    Address from_address = new InternetAddress(from, displayName);   
                    msg.setFrom(from_address);   
                }catch(java.io.UnsupportedEncodingException e){   
                    e.printStackTrace();   
                }
                Address[] addrs=InternetAddress.parse(to);
                msg.setRecipients(Message.RecipientType.TO,addrs);   
                if(!cc.equals(""))
                	msg.setRecipient(Message.RecipientType.CC,new InternetAddress(cc));
                if(!bcc.equals(""))
                	msg.setRecipient(Message.RecipientType.BCC,new InternetAddress(bcc));
                msg.setSubject(subject);   
                Multipart mp = new MimeMultipart();   
                MimeBodyPart mbp = new MimeBodyPart();   
                mbp.setContent(content.toString(), "text/html;charset=gb2312");   
                mp.addBodyPart(mbp); 
                mbp=new MimeBodyPart(); 
                System.out.println("发送附件："+filemap.get("realfilename"));
                FileDataSource fds=new FileDataSource((String)filemap.get("realfilename")); //得到数据源   
                mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart   
                try{
                	//System.out.println("要发送的附件名："+fds.getName());
                	mbp.setFileName(MimeUtility.encodeText((String)filemap.get("filename")));  //得到文件名同样至入BodyPart   
                }catch(UnsupportedEncodingException e){
                	mbp.setFileName(fds.getName());
                }
                mp.addBodyPart(mbp);
                /*
                if(!fmap.isEmpty()){//有附件   
                    Enumeration efile=fmap.elements();   
                    if(efile.hasMoreElements()){    
                        mbp=new MimeBodyPart();   
                        filemap=(HashMap)efile.nextElement(); //选择出每一个附件map   
                        System.out.println("发送附件："+filemap.get("realfilename"));
                        FileDataSource fds=new FileDataSource((String)filemap.get("realfilename")); //得到数据源   
                        mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart   
                        try{
                        	//System.out.println("要发送的附件名："+fds.getName());
                        	mbp.setFileName(MimeUtility.encodeText((String)filemap.get("filename")));  //得到文件名同样至入BodyPart   
                        }catch(UnsupportedEncodingException e){
                        	mbp.setFileName(fds.getName());
                        }
                        mp.addBodyPart(mbp);
                        file.removeElement(mbp);
                    }                                
                } 
                */   
                msg.setContent(mp); //Multipart加入到信件   
                msg.setSentDate(new Date());     //设置信件头的发送日期   
                //msg.setHeader("Content-Transfer-Encoding","base64");
          	  	msg.setHeader("X-Mailer","TurboMail Sender");
          	  	msg.setHeader("X-Priority",Priority);
          	  	msg.setHeader("Disposition-Notification-To",from);
                //发送信件   
                msg.saveChanges();                    
                trans.sendMessage(msg, msg.getAllRecipients());
                System.out.println("发送完成时间："+new Date());
                try{
                	if(i<file.size()-1)
                		Thread.sleep(5000);
    	        }catch(Exception ex){	
    	        }    	        
            }               
            trans.close();
            session = null;   	        
        }catch(AuthenticationFailedException e){      
             map.put("state", "failed");   
             message="邮件发送失败！错误原因：\n"+"身份验证错误!";   
             e.printStackTrace();    
        }catch (MessagingException e) {   
             message="邮件发送失败！错误原因：\n"+e.getMessage();   
             map.put("state", "failed");   
             e.printStackTrace();   
             Exception ex = null;   
             if ((ex = e.getNextException()) != null) {   
                 System.out.println(ex.toString());   
                 ex.printStackTrace();   
             }    
        }catch(Exception e){
        	e.printStackTrace();
        }
        
        //System.out.println("\n提示信息:"+message);   
        map.put("message", message);         
        return map;   
    } 
    public static void main(String args[])throws Exception{
    	long a=System.currentTimeMillis();
    	System.out.println(a);
    }
	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}
	 public HashMap sendValidateEmail(String uid,String requestmail,String subject,String code) throws Exception{
		 ResourceBundle mailconfig=com.knife.blog.service.Config.getMailconfig(); 
		 String ip=mailconfig.getString("com.knife.blog.ip");
		 subject="博客系统找回密码";
		 String content="尊敬的 <font color=\"red\">"+requestmail+"</font> 你好:<br><br>";
		 content=content+"&nbsp;&nbsp;&nbsp;&nbsp;点击下面的链接完成密码找回：<br>";
		 String url="http://"+ip+"/blogUser.do?parameter=resetPassword&u="+uid+"&v="+code;
		 content=content+"&nbsp;&nbsp;&nbsp;&nbsp;<a href=\""+url+"\" target=\"_blank\">"+url+"</a><br>";
		 content=content+"&nbsp;&nbsp;&nbsp;&nbsp;<font color=\"darkslateblue\">(5分钟后此链接失效，您将需要重新提交找回密码需求)</font><br>";
		 content=content+"&nbsp;&nbsp;&nbsp;&nbsp;<font color=\"darkslateblue\">(如果您错误地收到了此电子邮件，您无需执行任何操作)</font>";
	     String smtp=mailconfig.getString("com.knife.blog.smtp");
	     String needauth=mailconfig.getString("com.knife.blog.needauth");
	     String mailpass=mailconfig.getString("com.knife.blog.mailpass");
	     String mailfrom=mailconfig.getString("com.knife.blog.email");
		 SendMail objMail = new SendMail();    	
		 objMail.setFrom(mailfrom);
		 objMail.setTo(requestmail);    	
		 objMail.setDisplayName("");
		 objMail.setSmtpServer(smtp);
		 boolean auth=false;
		 if(needauth.equals("1")){
			 auth=true;
		 }	
		 objMail.setIfAuth(auth);
		 objMail.setPassword(mailpass);
		 objMail.setUserName(mailfrom);
		 objMail.setSubject(subject);
		 objMail.setContent(content);
		 HashMap objMap = objMail.send();
		 System.out.println("发送：" + objMap.get("state"));
		 System.out.println("信息：" + objMap.get("message"));
		 return objMap;
	 }
}   
